package com.itheima.annotion;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/*拦截器*/
public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Autowired
    private JedisPool jedisPool;

    /*执行controller之前的处理方法*/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null || token == "" || token.equals( "null")){

            /*前端没有传回token，未授权*/
            loginNo(response);
            return false;
        }

        String jtoken = jedisPool.getResource().get(token);
        Member member = (Member)JSON.parseObject(jtoken,Member.class);

        if (member == null){
            /*jedis没有token，未授权*/
            loginNo(response);
            return false;
        }

        return true;
    }

    private void loginNo(HttpServletResponse response) throws IOException {
        Result result = new Result(false,"",401);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(JSON.toJSONString(result));
        writer.close();
    }


}
